<script setup lang="ts">
import type { ILoginRequest } from '@fl/api/iam-api'
import type { FormInstance, FormRules } from 'element-plus'
// import { Hide, View } from '@element-plus/icons-vue'

import { goodHouseLogin, goodHouseProfile, setPassword, updatePassword, useGetOrgInfo, userAuthInfo, userCurrentPrivileges, userCurrentUserInfo } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { cookieClear, getAccessToken, getDistrict, getIAMToken, setDistrict, setIAMToken, setToken } from '@fl/logics/authentication'
import { ElForm, ElFormItem } from 'element-plus'
import { encrypt } from '@fl/utils/SM4'
import { orgAppKey } from '@fl/utils/appKey'
import { useUserStoreWithOut } from '@fl/store/modules/user'
import WujieVue from 'wujie-vue3'

const { bus } = WujieVue

const { push } = useRouter()

type IForm = { orgAccount?: string } & Pick<ILoginRequest, 'password' | 'username'>

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<IForm>({
    password: '',
    username: '',
})

const rules = reactive<FormRules<IForm>>({
    orgAccount: [
        {
            message: '请输入企业号',
            required: true,
        },
    ],
    password: [
        {
            message: '请输入密码',
            required: true,
        },
    ],
    username: [
        {
            message: '请输入用户名',
            required: true,
        },
    ],
})
const modifyDialog = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
// const { isPending: isPendingLogin, mutateAsync } = userLogin()
const { isLoading: isLoadingUserInfo, refetch: refetchUserInfo } = userCurrentUserInfo(false)
const { isLoading: isLoadingPrivilege, refetch: refetchPrivilege } = userCurrentPrivileges(false)
const { isLoading: isLoadingOrgInfo, refetch: refetchOrgInfo } = useGetOrgInfo(false)
const modifyForm = reactive<RuleForm>({
    oldPassword: '',
    newPassword: '',
    comfirmPassword: '',
})
const loading = ref(false)
const userId = ref('')
const isPassword = ref('')
const modifyFormRef = ref<FormInstance>()
const ryParams = ref<any>({})

onMounted(() => {
    window.localStorage.clear()
    cookieClear()
})

function validatePass(rule: any, value: any, callback: any) {
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,16}$/
    if (value === '') {
        callback(new Error('请输入新密码'))
    }
    else {
        if (!reg.test(value))
            callback('请输入8-16位密码，包含大写字母、小写字母、数字、特殊字符')
    }
    callback()
}
function validateConfirmPass(rule: any, value: any, callback: any) {
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,16}$/
    if (value === '') {
        callback(new Error('请确认新密码'))
    }
    else {
        if (!reg.test(value))
            callback('请输入8-16位密码，包含大写字母、小写字母、数字、特殊字符')
        if (value !== modifyForm.newPassword)
            callback('两次输入的密码不一致')
    }
    callback()
}
const modifyRules = reactive({
    oldPassword: [{ message: '请输入旧密码', trigger: 'blur', required: true }],
    newPassword: [{ validator: validatePass, trigger: 'blur', required: true }],
    comfirmPassword: [{ validator: validateConfirmPass, trigger: 'blur', required: true }],
})
// const isPending = computed(() => isPendingLogin.value || isLoadingUserInfo.value || isLoadingPrivilege.value || isLoadingOrgInfo.value) // 是否正在请求中
async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return false

    const isValid = await formEl.validate()
    if (!isValid) {
        return false
    }
    // const result = await mutateAsync({
    //         password: ruleForm.password,
    //         username: `${ruleForm.orgAccount}-${ruleForm.username}`,
    //     })
    //     if (result) {
    //         await refetchUserInfo()
    //         await refetchPrivilege()
    //         await refetchOrgInfo()

    //         bus.$emit('passAndJump', getAccessToken(), '/index')
    //         push('/')

    //         userAuthInfo().then((res) => {
    //             window.sessionStorage.setItem('USER_ID', res.id)
    //         })
    //     }
    // 好房新接口
    loading.value = true
    const res = await goodHouseLogin({
        // password: '5e8edfd2a4930f6c60f78bdbc308f933',
        password: encrypt(ruleForm.password),
        username: `${ruleForm.orgAccount}-${ruleForm.username}`,
        appKey: orgAppKey[window.location.host],
    }).catch(() => {
        loading.value = false
    }).finally(() => {
        loading.value = false
    })
    // 按需求判断新接口里是否有old-token字段，有就说明新老并列，否则如果有access_token字段，有就走老逻辑，没有走新逻辑
    if (res && res['old-token']) {
        const data = {
            access_token: res['iam-token'],
            refresh_token: res['iam-token'],
        }
        const oldData = {
            access_token: res['old-token'].access_token,
            refresh_token: res['old-token'].refresh_token,
        }
        await setIAMToken(data)
        await setToken(oldData)
        isProfile()
    }
    else if (res?.access_token) {
        setToken(res)
        isProfile('ok')
    }
    else if (res && res['iam-token']) {
        // 新房的逻辑存appKey
        window.localStorage.setItem('appKey', orgAppKey[window.location.host])
        const data = {
            access_token: res['iam-token'],
            refresh_token: res['iam-token'],
        }
        if (data.refresh_token) {
            await setIAMToken(data)
            isProfile()
        }
    }
}
async function isProfile(toPage: string | undefined, from: string | undefined) {
    if (toPage) {
        await refetchUserInfo()
        await refetchPrivilege()
        await refetchOrgInfo()
        // bus.$emit('passAndJump', from ? getIAMToken() : getAccessToken(), '/index', from)
        // push('/')
        bus.$emit('passAndJump', from
            ? {
                    type: '好房',
                    token: getIAMToken(),
                    ext1: getDistrict(),
                }
            : getAccessToken(), '/index', from)
        push('/')

        userAuthInfo().then((res) => {
            window.sessionStorage.setItem('USER_ID', res.id)
        })
    }
    else {
        if (getIAMToken()) {
            goodHouseProfile({
                appKey: orgAppKey[window.location.host],
            }).then(async (res) => {
                console.log(res.iamAccountVo?.ext1)
                // 这个就是新逻辑的userInfo接口
                // 存储区信息 429006000000-天门 420100000000 -武汉
                setDistrict(res.iamAccountVo?.ext1)
                if (res.iamAccountVo?.iamEncryptPassword) {
                    isProfile('ok', 'newGoodHouse')
                }
                else {
                    modifyDialog.value = true
                    userId.value = res.iamAccountVo.id
                    isPassword.value = res.iamAccountVo.password
                }
            }).catch(() => {
                loading.value = false
            }).finally(() => {
                loading.value = false
            })
        }
    }
}

function submitModifyForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    formEl.validate((valid) => {
        if (valid) {
        // 按需求，判断没有密码时，调用设置密码接口，有密码时，调用修改密码接口
            if (isPassword.value) {
                updatePassword({
                    oldPassword: encrypt(modifyForm.oldPassword),
                    newPassword: encrypt(modifyForm.newPassword),
                    appKey: orgAppKey[window.location.host],
                }).then(() => {
                    modifyDialog.value = false
                    isProfile('ok', 'newGoodHouse')
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                }).catch(() => {
                    loading.value = false
                }).finally(() => {
                    loading.value = false
                })
            }
            else {
                setPassword({
                    newPassword: encrypt(modifyForm.newPassword),
                    id: userId.value,
                }).then(() => {
                    modifyDialog.value = false
                    isProfile('ok', 'newGoodHouse')
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                }).catch(() => {
                    loading.value = false
                }).finally(() => {
                    loading.value = false
                })
            }
        }
        else {
            console.log('error submit!')
        }
    })
}
function openEye(field: string) {
    if (field === 'newPassword')
        showPassword.value = !showPassword.value
    else
        showConfirmPassword.value = !showConfirmPassword.value
}
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="企业号"
                        prop="orgAccount"
            >
                <el-input v-model="ruleForm.orgAccount"
                          placeholder="请输入企业号"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="用户名"
                        prop="username"
            >
                <el-input v-model="ruleForm.username"
                          placeholder="请输入用户名"
                          size="large"
                          maxlength="20"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="密码"
                        prop="password"
            >
                <el-input v-model="ruleForm.password"
                          type="password"
                          show-password
                          placeholder="请输入密码"
                          size="large"
                          maxlength="20"
                />
            </ElFormItem>
        </div>

        <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="loading"
                       @click="submitForm(ruleFormRef)"
            >
                登录
            </SubmitBtn>
        </ElFormItem>
    </ElForm>

    <el-dialog v-model="modifyDialog"
               title="修改密码  "
               width="500"
               :show-close="false"
               :close-on-click-modal="false"
    >
        <div class="modify-password">
            <ElForm ref="modifyFormRef"
                    style="max-width: 600px"
                    :model="modifyForm"
                    :rules="modifyRules"
                    label-width="auto"
                    class="modify-form"
            >
                <ElFormItem label="旧密码"
                            prop="oldPassword"
                >
                    <el-input v-model.trim="modifyForm.oldPassword"
                              type="password"
                    />
                </ElFormItem>

                <ElFormItem label="新密码"
                            prop="newPassword"
                >
                    <el-input v-model.trim="modifyForm.newPassword"
                              :type="showPassword ? 'text' : 'password'"
                    >
                        <template #append>
                            <el-icon size="17"
                                     @click="openEye('newPassword')"
                            >
                                <View v-if="showPassword" />

                                <Hide v-else />
                            </el-icon>
                        </template>
                    </el-input>
                </ElFormItem>

                <ElFormItem label="确认密码"
                            prop="comfirmPassword"
                >
                    <el-input v-model.trim="modifyForm.comfirmPassword"
                              :type="showConfirmPassword ? 'text' : 'password'"
                    >
                        <template #append>
                            <el-icon size="17"
                                     @click="openEye('comfirmPassword')"
                            >
                                <View v-if="showConfirmPassword" />

                                <Hide v-else />
                            </el-icon>
                        </template>
                    </el-input>
                </ElFormItem>
            </ElForm>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary"
                           @click="submitModifyForm(modifyFormRef)"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
    background-color: transparent;
    // padding: 0;
    // width: 54px;
    cursor: pointer;
}
</style>
